//
//  MPReceiptController.m
//  MarkPlatform
//
//  Created by xiao6 on 2017/12/26.
//  Copyright © 2017年 AT. All rights reserved.
//

#import "MPReceiptController.h"
#import "ATTextView.h"
#import "ATAreaPicker.h"
#import "MPCompanyMoneyRecordController.h"
#import "MPWalletModel.h"

@interface MPReceiptController ()

@property (nonatomic, strong) UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UIButton *companySpotButton;// 选中和不选中的点,仅用于显示
@property (weak, nonatomic) IBOutlet UIButton *personSpotButton;
// 企业
@property (weak, nonatomic) IBOutlet UITextField *companyNameField;
@property (weak, nonatomic) IBOutlet UITextField *companyTaxNumField;
@property (weak, nonatomic) IBOutlet UITextField *companyRecieptContentFiled;
@property (weak, nonatomic) IBOutlet UITextField *companyAmountField;
@property (weak, nonatomic) IBOutlet UITextField *companyPhoneField;
@property (weak, nonatomic) IBOutlet UITextField *companyAreaFiled;// userinteraction为no,仅用于显示文字
@property (weak, nonatomic) IBOutlet ATTextView  *companyAddressTextView;
// 个人
@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (nonatomic, weak) IBOutlet UITextField *personRecieptContentField;
@property (nonatomic, weak) IBOutlet UITextField *personAmountField;
@property (nonatomic, weak) IBOutlet UITextField *personPhoneField;
@property (nonatomic, weak) IBOutlet UITextField *personAreaFiled;
@property (nonatomic, weak) IBOutlet ATTextView  *personAddressTextView;

@property (nonatomic, strong) UIView *typeView;   // 第一行发票类型
@property (nonatomic, strong) UIView *receiptView;
@property (nonatomic, strong) UIView *companyReceiptView;
@property (nonatomic, strong) UIView *personReceiptView;
@property (nonatomic, strong) UIButton *applyButton;
@property (nonatomic, strong) UILabel *tipLabel;

@property (nonatomic, strong) MPWalletCompanyModel *wallet;

@end

@implementation MPReceiptController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showNavTitle:@"钱包" backItem:YES];
    [self setNavRightItemWithTitle:@"明细" action:@selector(didClickRightItem)];
    [self setupViews];
    [self clickCompany];
    
    [MBProgressHUD graceShowMessage:nil toView:self.view completion:^(MBProgressHUD *hud) {
        [MPHttpTool POST:[NSString stringWithFormat:@"business/wallet/queryInvoiceAmount/%@", [ATLocal user].userId] params:nil success:^(NSURLSessionDataTask *task, ATApiResult *result) {
            [hud hideAnimated:YES];
            self.wallet = [MPWalletCompanyModel modelWithJSON:result.data];
            [self updateDisplay];
        } failure:^(NSString *errorMsg) {
            [hud hideWithMessage:errorMsg completion:^{
                [self goBack];
            }];
        }];
    }];
}

#pragma mark - action

- (void)didClickRightItem {
    [self.navigationController pushViewController:[MPCompanyMoneyRecordController vcWithWalletId:self.wallet.Id] animated:YES];
}

- (IBAction)selectArea {
    [self.view endEditing:YES];
    ATPickerView *picker = [[ATPickerView alloc] init];
    ATAreaPicker *areaView = [[ATAreaPicker alloc] init];
    [picker.contentView addSubview:areaView];
    [areaView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(areaView.superview);
    }];
    @weakify(areaView)
//    [areaView setBlockForControlEvents:UIControlEventValueChanged block:^(id  _Nonnull sender) {
//        @strongify(areaView)
//        NSLog(@"%@", areaView.areaModel);
//    }];
    [picker show];
    [picker setDismissCompletion:^(ATSheetView *sheet, BOOL confirm) {
        @strongify(areaView)
        NSLog(@"%@ %@", areaView.areaModel, @(confirm));
        if (!areaView.areaModel) {
            
        }
        if (confirm) {
            NSString *areaString = [NSString stringWithFormat:@"%@%@%@",areaView.areaModel.state,areaView.areaModel.city,areaView.areaModel.district ? areaView.areaModel.district : @""];
            if (self.companySpotButton.selected) {
                self.companyAreaFiled.text = areaString;
            }
            else {
                self.personAreaFiled.text = areaString;
            }
        }
    }];
}
- (IBAction)clickCompany {
    self.companySpotButton.selected = YES;
    self.personSpotButton.selected = NO;
    
    [self.receiptView addSubview:self.companyReceiptView];
    [self.personReceiptView removeFromSuperview];

    [self.companyReceiptView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(@0);
        make.height.equalTo(@445);
    }];
    
    [self updateDisplay];
}
- (IBAction)clickPerson {
    self.companySpotButton.selected = NO;
    self.personSpotButton.selected = YES;
    
    [self.receiptView addSubview:self.personReceiptView];
    [self.companyReceiptView removeFromSuperview];
    
    [self.personReceiptView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(@0);
        make.height.equalTo(@394);
    }];
    
    [self updateDisplay];
}

- (void)updateDisplay {
    self.personPhoneField.text = [ATLocal user].tel;
    self.personRecieptContentField.text = self.wallet.content;
    self.personAmountField.text = [NSString stringWithFormat:@"%.2f", self.wallet.amount];
    self.companyPhoneField.text = [ATLocal user].tel;
    self.companyRecieptContentFiled.text = self.wallet.content;
    self.companyAmountField.text = [NSString stringWithFormat:@"%.2f", self.wallet.amount];
    self.companyAmountField.userInteractionEnabled = NO;
    self.personAmountField.userInteractionEnabled = NO;
}

- (void)applyReceipt {
    NSInteger type;
    NSString *name,*texNumber,*content,*amount,*tel,*district,*address;
    if (self.companySpotButton.selected) {// 企业
        if (self.companyNameField.text.length < 2) {
            [MBProgressHUD showMessage:@"请输入企业名称"];
            return;
        }
        if (self.companyTaxNumField.text.length > 32 || self.companyTaxNumField.text.length < 2) {
            [MBProgressHUD showMessage:@"请输入正确税号"];
            return;
        }
        if (self.companyAmountField.text.floatValue <= 0) {
            [MBProgressHUD showMessage:@"您没有可开票金额"];
            return;
        }
        if (self.companyPhoneField.text.length != 11) {
            [MBProgressHUD showMessage:@"请输入联系人电话"];
            return;
        }
        if (self.companyAreaFiled.text.length == 0) {
            [MBProgressHUD showMessage:@"请选择所在区域"];
            return;
        }
        if (self.companyAddressTextView.text.length == 0) {
            [MBProgressHUD showMessage:@"请填写详细地址"];
            return;
        }
        type = 0;// 企业
        name = self.companyNameField.text;
        texNumber = self.companyTaxNumField.text;
        content = self.companyRecieptContentFiled.text;
        amount = self.companyAmountField.text;
        tel = self.companyPhoneField.text;
        district = self.companyAreaFiled.text;
        address = self.companyAddressTextView.text;
    }
    else {
        if (self.nameField.text.length < 2 || self.nameField.text.length > 32) {
            [MBProgressHUD showMessage:@"请输入姓名"];
            return;
        }
        if (self.personAmountField.text.floatValue <= 0) {
            [MBProgressHUD showMessage:@"您没有可开票金额"];
            return;
        }
        if (self.personPhoneField.text.length != 11) {
            [MBProgressHUD showMessage:@"请输入正确的联系人电话"];
            return;
        }
        if (self.personAreaFiled.text.length == 0) {
            [MBProgressHUD showMessage:@"请选择所在区域"];
            return;
        }
        if (self.personAddressTextView.text.length <= 0) {
            [MBProgressHUD showMessage:@"请填写详细地址"];
            return;
        }
        type = 1;// 个人
        name = self.nameField.text;
        content = self.personRecieptContentField.text;
        amount = self.personAmountField.text;
        tel = self.personPhoneField.text;
        district = self.personAreaFiled.text;
        address = self.personAddressTextView.text;
    }
    
    [MBProgressHUD graceShowMessage:nil toView:self.view completion:^(MBProgressHUD *hud) {
        [MPHttpTool POST:@"business/wallet/editInvoice"
                  params:@{@"userID" : SafeDicObj([ATLocal user].userId),
                           @"type":@(type),
                           @"name":SafeDicObj(name),
                           @"number":SafeDicObj(texNumber),
                           @"content":SafeDicObj(content),
                           @"amount":SafeDicObj(amount),
                           @"tel":SafeDicObj(tel),
                           @"district":SafeDicObj(district),
                           @"address":SafeDicObj(address)
                           }
                 success:^(NSURLSessionDataTask *task, ATApiResult *result) {
                     [hud hideWithMessage:@"申请发票成功" completion:^{
                         [self goBack];
                     }];
                 } failure:ATHttpFailureWithHud(hud)];
    }];
}

#pragma mark - privite

- (void)setupViews {
    [self.view addSubview:self.scrollView];
    if (@available(iOS 11.0, *)) {
        self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.scrollView addSubview:self.typeView];
    [self.scrollView addSubview:self.receiptView];
    [self.scrollView addSubview:self.applyButton];
    [self.scrollView addSubview:self.tipLabel];
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.offset(0);
    }];
    [self.typeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.width.equalTo(@(SCREEN_WIDTH));
        make.top.offset(NAVI_HIGHT);
        make.height.equalTo(@50);
    }];
    [self.receiptView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.typeView);
        make.top.equalTo(self.typeView.mas_bottom);
    }];
    [self.applyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.receiptView.mas_bottom).offset(30);
        make.height.equalTo(@45);
        make.left.offset(57);
        make.centerX.offset(0);
    }];
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.applyButton.mas_bottom).offset(15);
        make.left.right.offset(0);
        make.bottom.offset(-15.f);
    }];
}

#pragma mark - getters
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
    }
    return _scrollView;
}
- (UIView *)typeView {
    if (!_typeView) {
        _typeView = [[[NSBundle mainBundle] loadNibNamed:@"MPReceiptTypeView" owner:self options:nil] firstObject];
    }
    return _typeView;
}
- (UIView *)receiptView {
    if (!_receiptView) {
        _receiptView = [[UIView alloc] init];
    }
    return _receiptView;
}
- (UIView *)personReceiptView {
    if (!_personReceiptView) {
        _personReceiptView = [[NSBundle mainBundle] loadNibNamed:@"MPPersonReceiptView" owner:self options:nil][0];
    }
    return _personReceiptView;
}
- (UIView *)companyReceiptView {
    if (!_companyReceiptView) {
        _companyReceiptView = [[NSBundle mainBundle] loadNibNamed:@"MPCompanyReceiptView" owner:self options:nil][0];
    }
    return _companyReceiptView;
}
- (UIButton *)applyButton {
    if (!_applyButton) {
        _applyButton = [MPAppButton buttonWithTitle:@"申请发票" target:self action:@selector(applyReceipt)];
    }
    return _applyButton;
}
- (UILabel *)tipLabel {
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc] init];
        _tipLabel.text = @"发票金额小于300时,需要您自付运费(顺丰到付)";
        _tipLabel.font = [UIFont systemFontOfSize:13.f];
        _tipLabel.textColor = [UIColor colorWithRGB:0x999999];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _tipLabel;
}

@end
